//
//  FriendsControl.m
//  FreeTime
//
//  Created by  on 16/8/29.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "FriendsControl.h"
#import "Header.h"
#import "FriendsCell.h"
#import <MWPhotoBrowser.h>
#import "MyFriendControl.h"
#import "PushFriendCircleControl.h"


@interface FriendsControl ()<FriendCellDelegate,MWPhotoBrowserDelegate,UITextViewDelegate>{
    UIImageView * tableHeaderImg;
    NSInteger index;
    UILabel * nameLbl,*textViewPlace;
    UIButton * messageBtn,* iconBtn;
    UITextView * textV;
    UIView * tfView;
    NSIndexPath * indexePathCell;
    CGFloat tempH;
    CGFloat tempY;
    UITableViewCell * tempCell;
    
}

@end

@implementation FriendsControl
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setupRightBarItem];
    [self loadOrignData];
    [self setupUI];
    [self setupTF];
    [self addObserve];
}
#pragma mark -- selfStyle --
- (void)setupRightBarItem{
    UIImageView * menuImage = [[UIImageView alloc] initWithFrame:CGRectMake(50, 10, 20, 20)];
    menuImage.image = [UIImage imageNamed:@"login_space"];
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 70, 40);
//    rightBtn.backgroundColor = [UIColor blueColor];
    [rightBtn addSubview:menuImage];
    [rightBtn addTarget:self action:@selector(addCircle) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];

}


- (void)setupUI{
    self.navigationItem.title = @"朋友圈";
    self.tableView.frame = CGRectMake(0, -64, WindowWidth, WindowHeight);
    self.tableView.backgroundColor = DEBUG_CLOLR;
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.tableView addGestureRecognizer:tapGesture];

    tableHeaderImg = [ReduceCode creatImageVeiwWithFrame:CGRectMake(0, 0, WindowWidth, 280) imageName:@"123" isCorner:NO];
    tableHeaderImg.alpha = 0.8;
    UIImageView * maskV = [[UIImageView alloc] initWithFrame:tableHeaderImg.frame];
    maskV.image = [UIImage imageNamed:@"grey_bg_img-1"];
    [tableHeaderImg addSubview:maskV];
    
//    tableHeaderImg.image = [[UIImage imageNamed:@"123"] applyDarkEffect];
    iconBtn = [ReduceCode creatBtnWithFrame:CGRectMake(10, 160, 60, 60) btnTitle:@"" btnTitleColor:nil btnTitleFont:20 btnBackgroundColor:nil backgroundImage:[UIImage imageNamed:@"123"] isCorner:YES];
    nameLbl = [ReduceCode creatLabelWithFrame:CGRectMake(CGRectGetMaxX(iconBtn.frame)+10, CGRectGetMidY(iconBtn.frame)-7.5, 160, 15) title:@"可爱的西红柿" titleColor:[UIColor whiteColor] font:15 textAlignment:0];
    [tableHeaderImg addSubview:nameLbl];
    [tableHeaderImg addSubview:iconBtn];
    self.tableView.tableHeaderView = tableHeaderImg;

}
- (void)setupTF{

    tfView = [[UIView alloc] initWithFrame:CGRectMake(0, WindowHeight-64, WindowWidth, 40)];
    tfView.backgroundColor = [UIColor redColor];
    [self.view addSubview:tfView];

    [ToolUtil createLine:0 superView:tfView lift:0 width:WindowWidth hight:1 color:[ImageUtil colorWithRgb:0xe6e6e6]];
    textV = [[UITextView alloc] initWithFrame:CGRectMake(10, 6.5, WindowWidth-80, 27)];
    textV.returnKeyType = UIReturnKeySend;
    textV.scrollEnabled = YES;
    textV.bounces = YES;
    textV.userInteractionEnabled = YES;
//    textV.alwaysBounceVertical = YES;
    
    textV.backgroundColor = [UIColor brownColor];
    //    textV.layer.borderColor = [UIColor grayColor].CGColor;
    //    textV.layer.borderWidth = 1;
    textV.delegate = self;
    [tfView addSubview:textV];
    textViewPlace = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, WindowWidth-80, 30)];
    textViewPlace.font = FONT(14);
    textViewPlace.textColor = [ImageUtil colorWithRgb:0xcccccc];
    textViewPlace.text = @"输入评论内容...";
    //    textViewPlace.textAlignment = 0;
    [textV addSubview:textViewPlace];
    
    UIButton * sendBtn = [ReduceCode creatBtnWithFrame:CGRectMake(WindowWidth-60, 1, 60, 39) btnTitle:@"发送" btnTitleColor:HOME_COLOR btnTitleFont:15 btnBackgroundColor:[UIColor whiteColor] backgroundImage:nil isCorner:NO];
    [tfView addSubview:sendBtn];

}
- (void)loadOrignData{
    NSArray * nameArr = @[@"可爱的西红柿",@"这个大黄瓜毕竟没有温度",@"sa菇凉"];
    NSArray * timeArr = @[@"1月30",@"48分",@"11:39"];
    NSArray * contentArr = @[@"汉皇重色思倾国，御宇多年求不得。杨家有女初长成，养在深闺人未识。天生丽质难自弃，一朝选在君王侧。回眸一笑百媚生，六宫粉黛无颜色。春寒赐浴华清池，温泉水滑洗凝脂。侍儿扶起娇无力，始是新承恩泽时。云鬓花颜金步摇，芙蓉帐暖度春宵。春宵苦短日高起，从此君王不早朝。",@"承欢侍宴无闲暇，春从春游夜专夜。后宫佳丽三千人，三千宠爱在一身。金屋妆成娇侍夜，玉楼宴罢醉和春。姊妹弟兄皆列土，可怜光彩生门户。遂令天下父母心，不重生男重生女。骊宫高处入青云，仙乐风飘处处闻。缓歌慢舞凝丝竹，尽日君王看不足。渔阳鼙鼓动地来，惊破霓裳羽衣曲。九重城阙烟尘生，千乘万骑西南行。翠华摇摇行复止，西出都门百余里。六军不发无奈何，宛转蛾眉马前死。花钿委地无人收，翠翘金雀玉搔头。君王掩面救不得，回看血泪相和流。黄埃散漫风萧索，云栈萦纡登剑阁。峨嵋山下少人行，旌旗无光日色薄。蜀江水碧蜀山青，圣主朝朝暮暮情",@"这个大黄瓜毕竟没有温度,你还要吗?"];
    NSArray * imgArr = @[@"2",@"4",@"7"];
    NSArray * commentArr = @[@"0",@"3",@"5"];
    for (int i = 0; i<3; i++) {
        NSDictionary * dict = @{@"iconImg":@"123",@"name":nameArr[i],@"time":timeArr[i],@"content":contentArr[i],@"commentNum":commentArr[i],@"image":imgArr[i]};
        
        [self.dataArray addObject:dict];
    }

}
#pragma mark -- 通知 --
- (void)addObserve{
    //监听键盘更改frame
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShown:) name:UIKeyboardWillChangeFrameNotification object:nil];
    //监听键盘出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidApper:) name:UIKeyboardDidShowNotification object:nil];
}
#pragma mark tableViewMethord
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary * dict = [FriendsCell cellFrame:self.dataArray[indexPath.row] indexPath:indexPath];
    self.dataArray[indexPath.row] = dict;
    return [dict[@"cellHeight"] integerValue];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"FriendsCell";
     FriendsCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[FriendsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    cell.tag = 100+indexPath.row;
    cell.delegate = self;
//    FriendsCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell bindData:self.dataArray[indexPath.row] indexPath:indexPath];
    return cell;
}
#pragma mark -- cellDelegate -- 

- (void)didSelectLikeAndCommentBtn:(UIButton *)btn cell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath{
    indexePathCell = indexPath;
//    if (cell.tag-100 == indexPath.row) {
//        if (<#condition#>) {
//            <#statements#>
//        }
//    }
    
//    textV.text = nil;
//    textViewPlace.text = @"输入评论内容...";
    if (btn.tag == 200) {
        NSLog(@"评论啦");
        if (tempCell.tag != cell.tag) {
            [textV removeFromSuperview];
            [tfView removeFromSuperview];
            [self setupTF];
            [textV becomeFirstResponder];
            
        }else{
            [textV becomeFirstResponder];
        }
        
    }else if(btn.tag == 201){
        NSLog(@"喜欢我");
    }else if (btn.tag == 202){
        NSLog(@"lala");
        MyFriendControl * friendVC = [MyFriendControl new];
        [self.navigationController pushViewController:friendVC animated:YES];
        
    }
    tempCell = cell;
    
}


- (void)didSelectBtn:(id)view cell:(UITableViewCell *)cell imageArr:(NSArray *)imageArr{
    index = cell.tag;
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    browser.displayActionButton = NO;//右下角分享按钮是否显示
    browser.displayNavArrows = NO;//下面导航按钮
    browser.displaySelectionButtons = NO;//选中该图片按钮
    browser.alwaysShowControls = NO;//第一次进来是否显示导航栏
    browser.zoomPhotosToFill = YES;//是否充满屏幕
    browser.enableGrid = NO;
    browser.startOnGrid = NO;
    browser.enableSwipeToDismiss = YES;//显示的时候是否有淡入淡出动画
    [browser setCurrentPhotoIndex:[(UIButton *)view tag]-100];
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:browser];
    nav.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nav animated:YES completion:nil];
}
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    return [self.dataArray[index-100][@"image"] integerValue];
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    //    PictureModel *photo = _mPhotoArray[index];
//    UIImageView * imageV = cellImagArray[index];
    MWPhoto *mwphoto = [MWPhoto photoWithImage:[UIImage imageNamed:@"123"]];
    return mwphoto;
}
#pragma mark textViewDelegate
- (void)textViewDidChange:(UITextView *)textView;
{
    
    if ([ToolUtil isBlank:textView.text]) {
        textViewPlace.hidden = NO;
    }else {
        textViewPlace.hidden = YES;
    }
//    textView.frame = CGRectMake(textV.frame.origin.x, textV.frame.origin.y, textV.frame.size.width, textV.contentSize.height+8);
//    CGFloat offSetY = 0;
//    if (tempH == 0) {
//        offSetY = -4;
//    }else{
//        offSetY =textView.contentSize.height-tempH;
//        tempY = offSetY;
//    }
//    if (textV.contentSize.height == tempH || tempH == 0) {
//        
//    }else{
////        tfView.frame = CGRectMake(tfView.frame.origin.x, tfView.frame.origin.y-(textView.contentSize.height-tempH), tfView.frame.size.width, textV.contentSize.height+20);
//    }
////    NSLog(@"textViewFrame == %@",[NSValue valueWithCGRect:textView.frame]);
////    NSLog(@"tfViewFrame == %@",[NSValue valueWithCGRect:tfView.frame]);
//    NSLog(@"tfView.frame.size.height = %f",tfView.frame.size.height);
//    tempH = textView.contentSize.height;


}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{
    if ([text isEqualToString:@"\n"]) {
//        if ([ToolUtil isBlank:textView.text]) {
//            return NO;
//        }else{
            [textView resignFirstResponder];
            return NO;
//        }
        
    }
    return YES;
}

#pragma mark -- 通知事件 --
- (void)keyboardDidApper:(NSNotification *)notification
{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:indexePathCell.row inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
- (void)keyBoardShown:(NSNotification *)notification
{
//    textV.text = nil;

//    NSLog(@"keyBoardShown %@",notification.userInfo);
    //取出键盘的frame
    CGRect rect = [notification.userInfo[@"UIKeyboardFrameEndUserInfoKey"] CGRectValue];
    //取出键盘弹出的动画时长
    CGFloat animationDuration = [notification.userInfo[@"UIKeyboardAnimationDurationUserInfoKey"]floatValue];
    //根据键盘frame的y值减去根视图的高度得到需要上移的值
    CGFloat offsetY = 0;
    if (rect.origin.y<WindowHeight) {
        
//        offsetY = rect.origin.y - self.view.size.height-64-tfView.frame.size.height;
        offsetY = rect.origin.y - self.view.size.height-64-tfView.frame.size.height;

    }else{
        
       offsetY = rect.origin.y - self.view.size.height-64;
//        tfView.frame = CGRectMake(0, WindowHeight-64, WindowWidth, tfView.frame.size.height);
  
    }
    
//    NSLog(@"tfView.frame.size.height = %f",tfView.frame.size.height);
//    NSLog(@"offsetY=%f",offsetY);
    //让根视图平滑的上移
    [UIView animateWithDuration:animationDuration animations:^{
        //让根视图整体上移
        self.view.transform = CGAffineTransformMakeTranslation(0, offsetY);
        
    }];
}
#pragma mark -- 响应事件 --
//处理轻拍手势
- (void)handleTapGesture:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
- (void)addCircle{
    /*
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * albumAction = [UIAlertAction actionWithTitle:@"从相册选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    UIAlertAction * camAction = [UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    UIAlertAction * cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }];
    [alertController addAction:albumAction];
    [alertController addAction:camAction];
    [alertController addAction:cancleAction];
    [self presentViewController:alertController animated:YES completion:nil];
     */
    [self presentViewController:[PushFriendCircleControl new] animated:YES completion:nil];
    
    
}
@end
